import { useUserStore } from '@/stores/modules';
import { Modal, message } from 'ant-design-vue';
import axios, { type AxiosRequestConfig, type AxiosResponse } from 'axios';
import qs from 'qs';
import { useRouter } from 'vue-router';
import errorCode from '@/constant/errorCode';
import { debounce, download } from '../utils';

const router = useRouter();
const service = axios.create({
  baseURL: VITE_BASE_API_URL,
  paramsSerializer: (params) => qs.stringify(params, { encode: true }),
});

service.interceptors.request.use((config) => {
  const userStore = useUserStore();
  const needToken = config.needToken !== false;

  if (needToken) {
    config.headers['Authorization'] = `Bearer ${userStore.token}`;
  }

  if (config.responseType === 'blob' && !config.fetchOptions?.noEncoded) {
    config.data = qs.stringify(config.data);
    config.headers['Content-Type'] = 'application/x-www-form-urlencoded';
  }

  return config;
});

service.interceptors.response.use((response) => {
  if (
    response.config.responseType === 'blob' &&
    response.data instanceof Blob
  ) {
    const header = response.headers['content-disposition'];
    const match = header?.match(/filename=([^;]+)/);
    if (match) {
      const fileName = match[1];
      download(response.data, fileName);
      return Promise.resolve();
    } else {
      console.log('未获取到文件名，已返回 blob，请自行处理');
      return response.data;
    }
  }
  console.log('response', response);

  const code = response.data.code;
  const msg =
    errorCode[code as unknown as keyof typeof errorCode] ||
    response.data.msg ||
    errorCode['default'];

  if (code === 401) {
    handleTokenExpire();
  } else if (code === 500) {
    if (response.config.skipError !== true) {
      message.error(msg);
    }
    return Promise.reject(new Error(msg));
  }
  // if (!response.data.data) {
  //   response.data.data = {};
  // }
  return response.data;
});

function request<T>(config: AxiosRequestConfig): Promise<ResponseData<T>> {
  return service(config);
}

request.get = function <T>(
  url: string,
  config?: AxiosRequestConfig,
): Promise<ResponseData<T>> {
  return service.get(url, config);
};

request.post = function <T>(
  url: string,
  data?: any,
  config?: AxiosRequestConfig,
): Promise<ResponseData<T>> {
  return service.post(url, data, config);
};

request.put = function <T>(
  url: string,
  data?: any,
  config?: AxiosRequestConfig,
): Promise<ResponseData<T>> {
  return service.put(url, data, config);
};

request.delete = function <T>(
  url: string,
  config?: AxiosRequestConfig,
): Promise<ResponseData<T>> {
  return service.delete(url, config);
};

const handleTokenExpire = debounce(() => {
  Modal.warning({
    title: '系统提示',
    content: '您的登录信息已过期，请重新登录！',
    okText: '重新登录',
    centered: true,
    onOk() {
      useUserStore()
        .logout()
        .then(() => {
          router.replace('/login');
        });
    },
  });
}, 300);

export default request;
